//
//  ECUIVC_HomeCourse.m
//  Edu_iOS2018
//
//  Created by yanyan on 2018/1/4.
//  Copyright © 2018年 yanyan. All rights reserved.
//

#import "ECUIVC_HomeCourse.h"
#import "ECUICVCell_HomeScroll.h"
#import "ECUICVCell_HomeCategory.h"
#import "ECUICVCell_Home.h"
#import "ECUICVHeader_Home.h"
#import "ECUIVC_CourseDetail.h"
#import "ECUIView_HomeListNoData.h"
@interface ECUIVC_HomeCourse ()<UICollectionViewDelegate,UICollectionViewDataSource>
{
    UICollectionViewFlowLayout *flowout;
//    ECUIVC_CourseDetail *uivc_detail;
    NSInteger start;
    NSURLSessionDataTask *task;
}
@property(nonatomic,strong)ECUIView_HomeListNoData *nodataView;
@property(nonatomic,strong)NSMutableArray *dataSource;
@property(nonatomic,strong)UIButton *moreBtn;//查看更多课程
@end

@implementation ECUIVC_HomeCourse
@synthesize collectionView = _collectionView;
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    start = 0;
    self.collectionView.showsVerticalScrollIndicator = NO;
    if (self.model) {
        [self requestCourseListWithCategory:self.model];
    }

}
- (ECUIView_HomeListNoData *)nodataView
{
    if (!_nodataView) {
        _nodataView = [[ECUIView_HomeListNoData alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 200)];
        _nodataView.imageView.image = [UIImage imageNamed:@"image_list_nodata"];
//        _nodataView.textLabel.text = @"暂无相关课程";
    }
    _nodataView.textLabel.text = @"暂无相关课程";
    return _nodataView;
}
- (UIButton *)moreBtn{
    if (!_moreBtn) {
        _moreBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//        _moreBtn.frame = CGRectMake(kScreenWidth/2 - 100 *kPercentage/2, 0,100 * kPercentage, 50);
        _moreBtn.frame = CGRectMake(0, 0,kScreenWidth, 50);
        [_moreBtn setImage:[UIImage imageNamed:@"chomeTag_loadmore"]  forState:UIControlStateNormal];
        [_moreBtn setTitle:@"加载更多课程" forState:UIControlStateNormal];
        _moreBtn.titleLabel.font = [UIFont systemFontOfSize:13 * kPercentage];
        [_moreBtn setTitleColor:[UIColor colorWithHexString:@"#999999"] forState:UIControlStateNormal];
         CGSize size = [[_moreBtn titleForState:UIControlStateNormal] sizeWithAttributes:@{NSFontAttributeName: _moreBtn.titleLabel.font}];
        _moreBtn.titleEdgeInsets = UIEdgeInsetsMake(0, -20, 0, 20);
        _moreBtn.imageEdgeInsets = UIEdgeInsetsMake(10, size.width+5, 10, -size.width-5);
        [_moreBtn addTarget:self action:@selector(action_loadMore:) forControlEvents:UIControlEventTouchUpInside];
        _moreBtn.hidden = YES;
        [_moreBtn setBackgroundColor:[UIColor colorWithRed:0.9686 green:0.9686 blue:0.9686 alpha:1]];
    }
    return _moreBtn;
}
-(void)action_loadMore:(id)sender{
    
    [self requestCourseListWithCategory:self.model];
}
- (NSMutableArray *)dataSource
{
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}

- (void)setHomeData:(NSDictionary *)homeData
{
    _homeData = homeData;
    _model = [homeData valueForKey:@"object"];
     NSArray *listData = [ECModelData arrayForCourses:[homeData valueForKey:@"courses"]];
    start = listData.count;
    [self showNodataView:(!listData || listData.count <= 0)];
    [self.dataSource addObjectsFromArray:listData];
    if ([[homeData valueForKey:@"total"] integerValue] <= listData.count) {
        self.moreBtn.hidden = YES;
    } else {
        self.moreBtn.hidden = NO;
    }
}
- (void)showNodataView:(BOOL)flag {
    if (flag) {
        [self.collectionView addSubview:self.nodataView];
        _moreBtn.hidden = YES;
    } else {
        [self.nodataView removeFromSuperview];

    }
}

- (void)setModel:(PrimaryCategoryModel *)model
{
    
    if ([_model.modelId isEqualToString:model.modelId]) {
        if (task && task.state == NSURLSessionTaskStateCompleted) {
            if (self.dataSource.count == 0) {
                [self requestCourseListWithCategory:model];
            }
        }
        
    } else {
        _model = model;
        [self.dataSource removeAllObjects];
        start = 0;
        [self requestCourseListWithCategory:model];
    }

}

-(void)requestCourseListWithCategory:(PrimaryCategoryModel *)mo
{
    WeakSelf(weakSelf);
    DLog(@"-mo.modelId : %@----%@",mo.modelId,mo.title);
    [MBProgressHUD showHUDAddedTo:[[UIApplication sharedApplication] keyWindow] animated:YES];
  task = [HWHttpTool get:URL_CourseOfCategory params:@{@"categoryId":mo.modelId,@"start":@(start)} success:^(id json) {
        id data = [json valueForKey:@"data"];
        NSMutableArray *courses = [ECModelData arrayForCourses:[data valueForKey:@"resources"]];
        [weakSelf.dataSource addObjectsFromArray:courses];
        if (weakSelf.dataSource.count >= [[data valueForKey:@"total"] integerValue]) {
            weakSelf.moreBtn.hidden = YES;
        } else {
            weakSelf.moreBtn.hidden = NO;
            start = self.dataSource.count;
        }
        [MBProgressHUD hideHUD];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.4f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [weakSelf showNodataView:(weakSelf.dataSource.count <= 0)];

            [UIView performWithoutAnimation:^{
                [_collectionView reloadData];
            }];
            
            //            // 当前获取的课程数目与 total 比较
            BOOL flag = courses.count < [[[json valueForKey:@"data"] valueForKey:@"total"] integerValue];
          //  [weakSelf showMoreBtnLoadMore:flag];
            
        });
        
    } failure:^(NSError *error) {
        [MBProgressHUD hideHUD];
        if (weakSelf.dataSource.count <= 0) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.4f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [weakSelf showNodataView:(weakSelf.dataSource.count <= 0)];
                _nodataView.textLabel.text = @"网络请求失败";
                [UIView performWithoutAnimation:^{
                    [_collectionView reloadData];
                }];
            });
        } else {
            [MBProgressHUD showErrorMessage:@"网络请求失败"];
        }
       

    }];
}
- (void)addSubviews
{
    [super addSubviews];
    //添加 collectionview
    flowout = [[UICollectionViewFlowLayout alloc]init];
//        flowout.naviHeight = kNavHeight;//64;
    flowout.itemSize = CGSizeMake(kScreenWidth, 150);
    flowout.minimumInteritemSpacing = 0;
    flowout.minimumLineSpacing = 10;
    flowout.sectionInset = UIEdgeInsetsMake(0,7*kPercentage,10,7*kPercentage);
    flowout.headerReferenceSize = CGSizeMake(kScreenWidth, 50);
    _collectionView = [[UICollectionView alloc]initWithFrame:self.view.bounds collectionViewLayout:flowout];
    _collectionView.backgroundColor = [UIColor whiteColor];
    _collectionView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
//    _collectionView.bounces = NO;
    [_collectionView registerClass:[ECUICVCell_Home class] forCellWithReuseIdentifier:@"cell"];

    [_collectionView registerClass:[CYUICVHeader_base class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"footer"];
    // 下拉刷新
    WeakSelf(weakSelf);
    _collectionView.mj_header = [MJRefreshStateHeader headerWithRefreshingBlock:^{
//            [weakSelf refreshHomeVC];
    }];
    [self.view addSubview:_collectionView];
}
- (void)addBarButtons
{
    [super addBarButtons];
    self.title = @"";
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {

    if (!self.vcCanScroll) {
        scrollView.contentOffset = CGPointZero;
    }
    if (scrollView.contentOffset.y <= 0) {
        self.vcCanScroll = NO;
        scrollView.contentOffset = CGPointZero;
        
        //到达顶部么，通知父视图改变状态
        [[NSNotificationCenter defaultCenter] postNotificationName:@"leaveTop" object:nil];
    }
}

#pragma mark - UICollectionView Delegate -

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.dataSource.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CYUICVCell_base *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    ((CYUICVCell_base *)cell).object = [self.dataSource objectAtIndex:indexPath.row];
    return cell;
}


-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
//    [collectionView deselectItemAtIndexPath:indexPath animated:YES];
    
        //详情
    if (self.block_selected) {
        self.block_selected([self.dataSource objectAtIndex:indexPath.row]);
    }
    
}

-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    
    if (kind == UICollectionElementKindSectionHeader) {
        CYUICVHeader_base *view;
        
            view = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header" forIndexPath:indexPath];
            view.backgroundColor = [UIColor whiteColor];
        
        return view;
    } else {
        CYUICVHeader_base *view = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"footer" forIndexPath:indexPath];
        
        if (indexPath.section == 0) {
            [view addSubview:self.moreBtn];
        }
        return view;
    }
}


#pragma mark - UICollectionViewDelegateFlowLayout -
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
   
        CGFloat width = floor((CGRectGetWidth(collectionView.frame) - 14 * kPercentage) / 2.0);
        return CGSizeMake(width, 128 * kPercentage);
}


- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section;
{
    if (section == 0) {
        return CGSizeZero;
    }
    return CGSizeMake(CGRectGetWidth(collectionView.frame), kProportion_Height(150));

}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section
{
        return CGSizeMake(CGRectGetWidth(collectionView.frame), 45);
}

//每个分区每行相隔的距离
-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
        return 0;
}
//每个分区每列相隔的最小距离
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    
        return 0;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
